<?php

namespace app\user\logic;

use app\common\exception\LogicException;
use app\model\UserFactory;

class UserFactoryLogic
{
    /**
     * @Description 猪厂选择列表
     * @author: zj
     * @param array $param
     * @time 2023/08/31 16:20:47
     * @return mixed
     */
    public function getSelectList(int $userId)
    {
        $userFactoryModel = new UserFactory();
        $list = $userFactoryModel->alias("uf")
            ->leftJoin("factory f","uf.factory_id = f.id")
            ->field("f.id,f.name")
            ->where("uf.user_id",$userId)
            ->where("uf.delete_time",$userFactoryModel::IS_DELETE_NO)
            ->select()
            ->toArray();
        return ['data' => $list];
    }

    /**
     * @Description 登录选择猪厂
     * @author: zj
     * @param int $id
     * @time 2023/08/31 16:42:23
     * @return array
     */
    public function selectFactory(int $id)
    {
        $userInfo = request()->user_info;
        $userFactoryModel = new UserFactory();
        $factory = $userFactoryModel->alias("uf")
            ->leftJoin("factory f","uf.factory_id = f.id")
            ->field("f.id,f.name,uf.id as user_factory_id,uf.user_id")
            ->where("uf.user_id",$userInfo['user_id'])
            ->where("uf.factory_id",$id)
            ->where("uf.delete_time",$userFactoryModel::IS_DELETE_NO)
            ->find();
        if (!$factory) {
            throw new LogicException("猪厂不存在");
        }

        // 写入缓存
        $userInfo['factory_id'] = $factory['id'];
        $userInfo['user_factory_id'] = $factory['user_factory_id'];
        $userInfo['factory'] = $factory['name'];
        $token = request()->header("token");
        $set = cache()->set("user_".$token,json_encode($userInfo,JSON_UNESCAPED_UNICODE),86400);

        if (!$set) {
            throw new LogicException("登录数据缓存失败");
        }

        return [
            'factory_id' => $factory['id'],
            'user_factory_id' => $factory['user_factory_id'],
            'factory' => $factory['name']
        ];
    }
}